#!/usr/bin/env python
# coding:utf-8
#用于普通的linux系统
from pexpect import pxssh
import pexpect
class linuxforssh:
    def __init__(self,ip,user,password):
        self.user = user
        self.ip = ip
        self.password = password
        self.s = pxssh.pxssh()
    def autolink(self):
        try:
            self.s.login(self.ip, self.user, self.password)
            return True
        except Exception as e:
            print("连接失败%s"%(e))
        return False
    def sendcommend(self,commend):
        self.s.sendline(commend)
        if self.s.prompt():
            return bytes.decode(self.s.before)
        else:
            return "命令失败"
    def logout(self):
        self.s.logout()
a = linuxforssh("192.168.20.210","root","root")

import time
if a.autolink():
    print(a.sendcommend("iostat -x -k -d 1"))
#用于单步执行命令
class Totalssh:
    def __init__(self,ip,root,password):
        self.ip = ip
        self.root = root
        self.password = password
        self.ssh = pexpect.spawn('ssh %s@%s ls' % (self.root,self.ip))
    def login(self):
        i = self.ssh.expect(['password:', 'continue connecting (yes/no)?'], timeout=5)
        print(i)
        if i == 0:
            self.ssh.sendline(self.password)
        elif i == 1:
            self.ssh.sendline('yes\n')
            self.ssh.expect('password: ')
            self.ssh.sendline(self.password)
        return True
    def command(self,cmd):
        self.ssh.sendline(cmd)
        return bytes.decode(self.ssh.read())
    def logout(self):
        self.ssh.close()

#有问题的
# def ssh_conn(ip,root,password,command,login_s="password:",run_s="$>#"):
#     try:
#         cmd = "ssh "+root +"@"+ip
#         child = pexpect.spawn(cmd)
#         ret = child.expect([pexpect.TIMEOUT,login_s],timeout=5)
#         if ret == 0:
#             print("连接错误,请核实IP是否正确")
#             return None
#         child.sendline(password)
#         child.expect(run_s)
#         data = ""
#         for i in command:
#             child.sendline(i)
#             child.expect(run_s)
#             data += bytes.decode(child.before) + "\n"
#         print(data)
#         child.close()
#     except Exception as e:
#         print("连接失败,请确认账号或者密码")
# cmd = ["df"]
# ssh_conn("192.168.20.210","root","root",cmd)